package com.car.serve.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.car.commons.core.model.Result;
import com.car.commons.web.util.StateUtil;
import com.car.serve.Param.PageServeShouHouParam;
import com.car.serve.Param.PageStoresShouHouParam;
import com.car.serve.Param.addServeShouHouParam;
import com.car.serve.client.OrderClient;
import com.car.serve.client.UserClient;
import com.car.serve.client.dto.findByUserIdDto;
import com.car.serve.client.dto.order.ServiceOrderInfoDto;
import com.car.serve.entity.ServeShouhou;
import com.car.serve.entity.ServeShouhouLog;
import com.car.serve.exception.ServeException;
import com.car.serve.mapper.ServeShouhouLogMapper;
import com.car.serve.mapper.ServeShouhouMapper;
import com.car.serve.service.ServeInfoService;
import com.car.serve.service.ServeShouhouLogService;
import com.car.serve.service.ServeShouhouService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 董旭
 * @since 2024-08-28
 */
@Service
public class ServeShouhouServiceImpl extends ServiceImpl<ServeShouhouMapper, ServeShouhou> implements ServeShouhouService {

    @Resource
    private ServeShouhouMapper serveShouhouMapper;
    @Resource
    private OrderClient orderClient;
    @Resource
    private UserClient userClient;
    @Resource
    private ServeShouhouService serveShouhouService;
    @Resource
    private ServeShouhouLogService serveShouhouLogService;
    @Resource
    private ServeShouhouLogMapper serveShouhouLogMapper;
    @Override
    public void addServeShouHou(addServeShouHouParam param) throws Exception {

        Result<ServiceOrderInfoDto> result = orderClient.findByServeNum(param.getServeNum());
        if (result.getCode()!=200)throw new ServeException(3000,"当前订单状态不是待服务状态");
        ServiceOrderInfoDto serviceOrderInfoDto = result.getData();
        if (ObjectUtil.isEmpty(serviceOrderInfoDto))throw new ServeException(3000,"该订单不存在");
        //判断订单是否为待售后状态
        if (!serviceOrderInfoDto.getOrderState().equals(StateUtil.SERVE_ORDER_STATE_NOT_SERVED)) {
            throw new ServeException(3001,"状态异常");
        }
        //获取门店ID
        Integer storesId = serviceOrderInfoDto.getStoresId();
        //获取当前系统时间
        String createTime = DateUtil.format(LocalDateTime.now(),"yyyy-MM-dd HH:mm:ss");
        //根据ID查询用户姓名
        Result<findByUserIdDto> userById = userClient.findUserById(param.getServeUserid());
        if (userById.getCode()!=200)throw new ServeException(3000,"不存在用户");
        String userName = userById.getData().getUserName();
        //新增售后
        ServeShouhou serveShouhou = BeanUtil.toBean(param, ServeShouhou.class);
        serveShouhou.setServeCause(param.getServeCause());
        serveShouhou.setServeStartime(createTime);
        serveShouhou.setServeUserid(param.getServeUserid());
        serveShouhou.setStoresId(storesId);
        //状态设置处理中
        serveShouhou.setServeState(1);
        serveShouhou.setServeNum(param.getServeNum());
        serveShouhou.setServeUsername(userName);
        serveShouhouMapper.insert(serveShouhou);
        //新增售后日志
        ServeShouhouLog serveShouhouLog = new ServeShouhouLog();
        //把状态设置为处理中
        serveShouhouLog.setServeLogState(1);
        serveShouhouLog.setShouhouId(serveShouhou.getShouhouId());
        serveShouhouLog.setServeLogTime(createTime);
        serveShouhouLog.setServeLogUserId(param.getServeUserid());
        serveShouhouLog.setServeLogUserName(userName);
        serveShouhouLog.setStoresId(storesId);
        serveShouhouLogService.save(serveShouhouLog);
    }

    @Override
    public Page<ServeShouhou> findBuyIdShouHou(PageServeShouHouParam param) throws Exception{
        Page<ServeShouhou> page = new Page<>(param.getPageNum() == null ? 1 : param.getPageNum(), param.getPageSize() == null ? 6 : param.getPageSize());
        QueryWrapper<ServeShouhou> wrapper = new QueryWrapper<>();
        // 添加当前用户的ID作为查询条件
        wrapper.eq("serve_userid", param.getUserId());
        //判断订单号是否为空
        if (ObjectUtil.isNotEmpty(param.getServeNum())) {
            wrapper.like("serve_num", param.getServeNum());
        }
        if (ObjectUtil.isNotEmpty(param.getServeState())){
            wrapper.eq("serve_state",param.getServeState());
        }
        Page<ServeShouhou> serveShouhouPage = serveShouhouMapper.selectPage(page, wrapper);
        return serveShouhouPage;
    }

    @Override
    public void finishShouhou(Integer shouHouId) throws Exception {
        System.out.println(shouHouId);
        ServeShouhou byId = serveShouhouService.getById(shouHouId);
        if (byId==null)throw new ServeException(3000,"当前售后不存在");
        String serveNum = byId.getServeNum();
        //把当前售后状态改为退款成功
        byId.setServeState(2);
        serveShouhouMapper.updateById(byId);
        //获取当前系统时间
        String createTime = DateUtil.format(LocalDateTime.now(),"yyyy-MM-dd HH:mm:ss");
        //修改完成并修改日志状态和时间
        ServeShouhouLog serveShouhouLog = serveShouhouLogService.getById(byId.getShouhouId());
        serveShouhouLog.setServeLogCompletiontime(createTime);
        //状态改为退款成功
        serveShouhouLog.setServeLogState(2);
        Result result=orderClient.refund(serveNum);
        serveShouhouLogMapper.updateById(serveShouhouLog);
    }

    @Override
    public void CancelShouhou(Integer shouHouId) throws Exception {
        ServeShouhou byId = serveShouhouService.getById(shouHouId);
        if (byId==null)throw new ServeException(3000,"当前售后不存在");
        //取消成功
        byId.setServeState(3);
        serveShouhouMapper.updateById(byId);
        //获取当前系统时间
        String createTime = DateUtil.format(LocalDateTime.now(),"yyyy-MM-dd HH:mm:ss");
        //修改完成并修改日志状态和时间
        ServeShouhouLog serveShouhouLog = serveShouhouLogService.getById(byId.getShouhouId());
        serveShouhouLog.setServeLogCompletiontime(createTime);
        //状态改为取消售后
        serveShouhouLog.setServeLogState(3);
        serveShouhouLogMapper.updateById(serveShouhouLog);
    }

    @Override
    public Page<ServeShouhou> getOrderInfoPage(PageStoresShouHouParam param) throws Exception {
        //根据当前登录ID查询门店信息
        Result<Integer> result = userClient.findStoresIdByClerkId(param.getClerkId());
        Integer storesId = result.getData();
        //根据门店ID去查询所有当前门店的售后
        Page<ServeShouhou> page = new Page<>(param.getPageNum() == null ? 1 : param.getPageNum(), param.getPageSize() == null ? 6 : param.getPageSize());
        QueryWrapper<ServeShouhou> wrapper = new QueryWrapper<>();
        // 添加当前的门店ID作为查询条件
        wrapper.eq("stores_id", storesId);
        //判断订单号是否为空
        if (ObjectUtil.isNotEmpty(param.getServeNum())) {
            wrapper.like("serve_num", param.getServeNum());
        }
        if (ObjectUtil.isNotEmpty(param.getServeState())){
            wrapper.eq("serve_state",param.getServeState());
        }
        // 添加排序规则，比如按照创建时间降序排序
        wrapper.orderByDesc("serve_startime");
        Page<ServeShouhou> serveShouhouPage = serveShouhouMapper.selectPage(page, wrapper);
        return serveShouhouPage;
    }
}
